package com.adgroup.doremon_ad;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import model.User;

import org.json.JSONException;
import org.json.JSONObject;

import util.Config;
import util.Utility;
import adapter.JsonParse;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

import database.Database;

public class LoginActivity extends SherlockActivity {

	EditText etEmail, etPassword;
	Button btnLogin;
	String gcmId = "";
	TextView tvForgetPass;
	Button btnRegiset;
	Handler handler = new Handler();
	ActionBar mActionBar;
	Button btnLoginGoogle, btnLoginFacebook;
	private Facebook facebook;
	SharedPreferences sharedPrefs;
	LinearLayout root;
	private AsyncFacebookRunner mAsyncRunner;
	private static final String[] PERMS = new String[] { "read_stream" ,"offline_access"};
	//google
	private static final int REQUEST_CODE_RESOLVE_ERR = 9000;

    private ProgressDialog mConnectionProgressDialog;
    
   /* Runnable runLoginGoogle = new Runnable() {
		
		@Override
		public void run() {
			if(mConnectionProgressDialog!=null && mConnectionProgressDialog.isShowing()){
				mConnectionProgressDialog.dismiss();
				mPlusClient.disconnect();
				Utility.ShowAlert(LoginActivity.this, getResources().getString(R.string.error), getResources().getString(R.string.login_error_googleplus));
			}
		}
	};*/
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	//	MenuInflater inflater = getSupportMenuInflater();
		//inflater.inflate(R.menu.menulogin, menu);
		return super.onCreateOptionsMenu(menu);
		
	}
	
	
	@Override
	public boolean onOptionsItemSelected(
			com.actionbarsherlock.view.MenuItem item) {
		switch (item.getItemId()) {
		
		case android.R.id.home:
			finish();
			break;
		default:
			break;  
		}
		return super.onOptionsItemSelected(item);
	}
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState); 
		setContentView(R.layout.login);
		
		 AdView mAdView = (AdView) this.findViewById(R.id.adView);
		    AdRequest adRequest = new AdRequest.Builder().build();
		    mAdView.loadAd(adRequest);
		
		
		/*mPlusClient = new PlusClient.Builder(LoginActivity.this, this, this)
        .setScopes("http://schemas.google.com/AddActivity", "http://schemas.google.com/BuyActivity")
        .setScopes("PLUS_LOGIN")  // Space separated list of scopes
        .build();
		// Progress bar to be displayed if the connection failure is not resolved.
		mConnectionProgressDialog = new ProgressDialog(this);
		mConnectionProgressDialog.setMessage("Signing in...");
*/
		//action bar
		mActionBar = getSupportActionBar();
		mActionBar.setDisplayHomeAsUpEnabled(false);
		mActionBar.setDisplayUseLogoEnabled(true);
		mActionBar.setHomeButtonEnabled(true);
		mActionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.background_actionbar));
		
		mActionBar.setTitle(getResources().getString(R.string.buttonlogin));
		
		facebook = new Facebook(getResources().getString(R.string.facebook_app_id));
		mAsyncRunner = new AsyncFacebookRunner(facebook);
		
		//mapping
		etEmail = (EditText) findViewById(R.id.editTextEmailLogin);
		etPassword = (EditText) findViewById(R.id.editTextPasswordLogin);
		btnLogin = (Button) findViewById(R.id.buttonLogin);
		tvForgetPass = (TextView) findViewById(R.id.textViewForgetPassword);
		btnRegiset = (Button) findViewById(R.id.buttonregisetinlogin);
		btnLoginFacebook = (Button) findViewById(R.id.buttonLoginFacebook);
		btnLoginGoogle = (Button) findViewById(R.id.buttonLoginGoogle);
		root = (LinearLayout) findViewById(R.id.rootLogin);
		
		root.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				try {
					imm.hideSoftInputFromWindow(etEmail.getWindowToken(), 0);
					imm.hideSoftInputFromWindow(etPassword.getWindowToken(), 0);
					
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		});
		///
		etEmail.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View arg0, boolean arg1) {
				if (arg1)
                {
                    //open keyboard
                    ((InputMethodManager) LoginActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(etEmail,
                            InputMethodManager.SHOW_FORCED);
                    etEmail.requestFocus();
                }
                else
                { //close keyboard
                    ((InputMethodManager) LoginActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                    		etEmail.getWindowToken(), 0);
                }
			}
		});
		etPassword.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View arg0, boolean arg1) {
				if (arg1)
                {
                    //open keyboard
                    ((InputMethodManager) LoginActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(etPassword,
                            InputMethodManager.SHOW_FORCED);
                    etPassword.requestFocus();
                }
                else
                { //close keyboard
                    ((InputMethodManager) LoginActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                    		etPassword.getWindowToken(), 0);
                }
			}
		});
		
		btnLoginGoogle.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Utility.ShowAlert(LoginActivity.this, "",getResources().getString(R.string.login_error_googleplus));
				/*handler.postDelayed(runLoginGoogle, Config.timeout);
				int resultCode = GooglePlayServicesUtil
						.isGooglePlayServicesAvailable(getApplicationContext());
				if (resultCode != ConnectionResult.SUCCESS) {
					mConnectionProgressDialog.dismiss();
					Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
							resultCode, LoginActivity.this, 69);
					if (dialog != null) {
						dialog.show();
					} else {						
						Utility.ShowAlert(LoginActivity.this, "Lỗi","Các dịch vụ của Google Play mà ứng dụng yêu cầu không được thiết bị hỗ trợ. Vui lòng liên hệ với nhà sản xuất để được hỗ trợ.");
					}
				}
				else{
					if (!mPlusClient.isConnected()) {
						if (mConnectionResult == null) {

						} else {
							try {
								mConnectionResult.startResolutionForResult(
										LoginActivity.this,
										REQUEST_CODE_RESOLVE_ERR);
							} catch (SendIntentException e) {
								// Try connecting again.
								mConnectionResult = null;
								mPlusClient.connect();
							}
						}
					}
				}*/
			}
		});
		
		btnLoginFacebook.setOnClickListener(new OnClickListener() {
			
			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View v) {
				
				facebook = new Facebook(getResources().getString(R.string.facebook_app_id));
		        mAsyncRunner = new AsyncFacebookRunner(facebook);
		        facebook.authorize(LoginActivity.this, PERMS, new LoginDialogListener());					
			}
		});
		
		//forget pass word
		tvForgetPass.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Intent i = new Intent(LoginActivity.this, ForgetPasswordActivity.class);
				startActivity(i);
			}
		});
		
		//register
		btnRegiset.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Intent i = new Intent(LoginActivity.this, RegisterActivity.class);
				startActivityForResult(i, Config.LoginToRegister); 
			}
		});
		
		//get gcm
		//new AsynGetGCM().execute();
		btnLogin.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				try {
					imm.hideSoftInputFromWindow(etEmail.getWindowToken(), 0);
					imm.hideSoftInputFromWindow(etPassword.getWindowToken(), 0);
					
				} catch (Exception e) {
					// TODO: handle exception
				} 
				String  gmail = etEmail.getText().toString();
				String pass = (etPassword.getText().toString());
				//check infor
				if(gmail.equalsIgnoreCase("")){
					new AlertDialog.Builder(LoginActivity.this)
					.setTitle(getResources().getString(R.string.errortitlelogin))
					.setMessage(getResources().getString(R.string.errornullusernameregister))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									setEditTextFocus(etEmail, true);
								}
					}).show();
				}
				else if(gmail.length()<6){
					new AlertDialog.Builder(LoginActivity.this)
					.setTitle(getResources().getString(R.string.errortitlelogin))
					.setMessage(getResources().getString(R.string.error6usernameregister))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									setEditTextFocus(etEmail, true);
								}
					}).show();
				}
				else if(pass.equalsIgnoreCase("")){
					new AlertDialog.Builder(LoginActivity.this)
					.setTitle(getResources().getString(R.string.errortitlelogin))
					.setMessage(getResources().getString(R.string.errornullpassregister))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									setEditTextFocus(etPassword, true);
								}
					}).show();
				}
				else if(pass.length()<6){
					new AlertDialog.Builder(LoginActivity.this)
					.setTitle(getResources().getString(R.string.errortitlelogin))
					.setMessage(getResources().getString(R.string.error6passregister))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									setEditTextFocus(etPassword, true);
								}
					}).show();
				}
				else{
					if(!Utility.isConnect(LoginActivity.this)){
						new AlertDialog.Builder(LoginActivity.this)
						.setTitle(getResources().getString(R.string.titleerrornetwork))
						.setMessage(getResources().getString(R.string.messageerrornetwork))
						.setNegativeButton(getResources().getString(R.string.setting), new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								
							}
						})
						.setPositiveButton(getResources().getString(R.string.cancel),
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
									}
						}).show(); 
					} 
					else{
						pass = Utility.md5(pass);
						String[] params = new String[] {gmail,pass};
						new AsyntaskLogin().execute(params);
					}
				}
			}
		});
		hideKeyboard(etEmail);
		//hideKeyboard(etPassword);
		
	}
	private class LoginDialogListener implements DialogListener {
		 
        @SuppressWarnings("deprecation")
		@Override
        public void onComplete(Bundle values) {  
        	int a = 4;
            mAsyncRunner.request("me", new IDRequestListener());
        }

        @Override
        public void onFacebookError(FacebookError e) {
        }

        @Override
        public void onError(DialogError e) {
        }

        @Override
        public void onCancel() {
        }
}
	private class IDRequestListener implements RequestListener {

        @Override
        public void onComplete(String response, Object state) {
                try {
                        
                        JSONObject json = Util.parseJson(response);

                        final String id = json.getString("id");
                        final String name = json.getString("name");
                        String access = facebook.getSession().getAccessToken();
						Date d = facebook.getSession().getExpirationDate();
						long milliseconds = d.getTime();
						SharedPreferences share = getSharedPreferences(
								"sharefilmllk", MODE_PRIVATE);
						SharedPreferences.Editor editor = share
								.edit();

						editor.putLong("access_expires",
								milliseconds);
						editor.putString("access", access);

						String email = json.getString("email");
						String birthday = "2012-12-12";//json.getString("birthday");
						final String nickname = json.getString("name");
						String username = json.getString("username");
						editor.putString("username", nickname);
						editor.commit();
						String gender = json.getString("gender");
						if(gender.toLowerCase().equalsIgnoreCase("male")){
							gender = "1";
						}
						else if(gender.toLowerCase().equalsIgnoreCase("female")){
							gender = "0";
						}
						String avatar = json.getString("id");
						avatar = "http://graph.facebook.com/"+avatar+"/picture";
						final String[] params = new String[] {email,username,birthday,nickname,gender,Config.typeFacebook,"1"};//1: facebook
						runOnUiThread(new Runnable() {
							public void run() {
								new AsyntaskLoginWithSocial().execute(params);									
							}
						});
						//String[] params = new String[] {email,username,birthday,nickname,gender,avatar,Config.typeFacebook,"1","gcmid"};//1: facebook
					//	new AsyntaskLoginWithSocial().execute(params);
							
                } catch (JSONException e) {
                      
                } catch (FacebookError e) {
                      
                }
        }

        @Override
        public void onIOException(IOException e, Object state) {
                
        }

        @Override
        public void onFileNotFoundException(FileNotFoundException e,
                        Object state) {
               
        }

        @Override
        public void onMalformedURLException(MalformedURLException e,
                        Object state) {
                
        }

        @Override
        public void onFacebookError(FacebookError e, Object state) {
                
        }

}
	private Session.StatusCallback callback = new Session.StatusCallback() 
	{
	    @Override
	    public void call(Session session, SessionState state, Exception exception) 
	    {
	        Log.e("SKFBDemo", "Session.StatusCallback state="+state.toString());
	    }
	};
	private static final List<String> PERMISSIONS = Arrays.asList("email", "user_groups");

	/*private StartAppAd startAppAd = new StartAppAd(this); 
	@Override 
	public void onResume(){ 
	      super.onResume(); 
	      startAppAd.onResume(); 
	  } 
	@Override 
	  public void onPause() { 
	      super.onPause(); 
	      startAppAd.onPause(); 
	  } 
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		
		if(keyCode==KeyEvent.KEYCODE_HOME){
			 startAppAd.showAd(); 
			    startAppAd.loadAd(); 
		}
		return super.onKeyDown(keyCode, event);
	}*/
	@SuppressWarnings("deprecation")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		facebook.authorizeCallback(requestCode, resultCode, data);
		if(requestCode==Config.LoginToRegister && resultCode==RESULT_OK){//register then login
			Log.d("log","return");
			progress = ProgressDialog.show(LoginActivity.this, "",
					getResources().getString(R.string.logining), true);
			handler.postDelayed(new Runnable() {
				
				@Override
				public void run() {
					progress.dismiss();
					Intent returnIntent = new Intent();
					returnIntent.putExtra("result", data.getStringExtra("result"));
					setResult(RESULT_OK, returnIntent);
					finish();
				}
			}, 1000);			
		}
		if (requestCode == REQUEST_CODE_RESOLVE_ERR && resultCode == RESULT_OK) {
	      //  mConnectionResult = null;
	        //mPlusClient.connect();
	    }
		if(resultCode == RESULT_OK && requestCode == Session.DEFAULT_AUTHORIZE_ACTIVITY_CODE)
	    {
	        Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);

	        final Session session = Session.getActiveSession(); 
	        if (session != null && !session.isClosed()) 
	        {
	            Log.e("SKFBDemo", "Login successful");
	        }
	        else
	        {
	            Log.e("SKFBDemo", "Facebook session not opened");
	        }
	    }
	}
	/*@Override
    protected void onStart() {
        super.onStart();
        mPlusClient.connect();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mPlusClient.disconnect();
    }
    @Override
    protected void onResume() {
    	// TODO Auto-generated method stub
    	super.onResume();
    	if (adView != null) {
			adView.resume();
		}
    	handler.postDelayed(runLoginGoogle, Config.timeout);
    }*/
    @Override
    protected void onDestroy() {
    	// TODO Auto-generated method stub
    	super.onDestroy();
    	
    	//handler.removeCallbacks(runLoginGoogle);
    }
	/*@Override
	public void onConnectionFailed(ConnectionResult result) {
	       if (mConnectionProgressDialog.isShowing()) {
	               // The user clicked the sign-in button already. Start to resolve
	               // connection errors. Wait until onConnected() to dismiss the
	               // connection dialog.
	               if (result.hasResolution()) {
	                       try {
	                               result.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
	                       } catch (SendIntentException e) {
	                               mPlusClient.connect();
	                       }
	               }
	       }

	       // Save the intent so that we can start an activity when the user clicks
	       // the sign-in button.
	       mConnectionResult = result;
	}
	String accountName;
	@Override
	public void onConnected(Bundle connectionHint) {
	 // We've resolved any connection errors.
	  mConnectionProgressDialog.dismiss();
	  progress = ProgressDialog.show(LoginActivity.this, "", getResources().getString(R.string.connecting),
				true);
		accountName = mPlusClient.getAccountName();
		mConnectionProgressDialog.show();
		
		//mPlusClient.loadPerson(LoginActivity.this, "me");
	}
	// ----Success Load Info Google---//
	public void onPersonLoaded(ConnectionResult status, Person person) {
		// TODO Auto-generated method stub
		if (status.getErrorCode() == ConnectionResult.SUCCESS) {////email,birthday,nickname,gender,avatar,gcmId,"1"-> facebook
			String[] params = new String[] { accountName,person.getBirthday(),person.getDisplayName(),
					person.getGender() + "",person.getImage().toString(),gcmId, "2" };//google plus
			new AsyntaskLoginWithSocial().execute(params);
		}
	}*/
	//get gcm id
	/*class AsynGetGCM extends AsyncTask<Void, Void, Void>
	{

		@Override
		protected Void doInBackground(Void... params) {
			gcm = GoogleCloudMessaging.getInstance(LoginActivity.this);
			try {
				gcmId = gcm.register(Configuration.SENDERID);
				Log.d("log","gcm:"+gcmId);
			} catch (IOException e) {
				gcmId = "";
				Log.e("error",e.getMessage());
			}
			return null;
		}
		
	}
	*/
	private ProgressDialog progress;
	//asyntask login
	class AsyntaskLogin extends AsyncTask<String, Void, String>
	{
		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progress = ProgressDialog.show(LoginActivity.this, "",
					getResources().getString(R.string.logining), true);
		}
		@Override
		protected String doInBackground(String... params) {
			return JsonParse.getInstance().loginAccount(params,LoginActivity.this);
			//gmail,pass,platform,gcmId,type
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			progress.dismiss();
			try {
				JSONObject json = new JSONObject(result);
				String r = json.getString(Config.result);
				if(r.equalsIgnoreCase(Config.norow)){
					AlertDialog.Builder alert = new AlertDialog.Builder(LoginActivity.this);
					alert.setTitle(getResources().getString(R.string.errortitlelogin));
					alert.setMessage(getResources().getString(R.string.errormessagelogin));
					alert.setNeutralButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							setEditTextFocus(etEmail, true);
						}
					});
					alert.show();
					
				}
				else{
					JSONObject rjson = json.getJSONArray(Config.result).getJSONObject(0);
					String gmai = rjson.getString(User.keyGmail);
					String nickname = rjson.getString(User.keyNickName);
					//String userName = rjson.getString(User.keyUserName);
					String birthday = rjson.getString(User.keyBirthday);
					String type = rjson.getString(User.keyType);
					String gender = rjson.getString(User.keyGender);
					String time = rjson.getString(User.keyTime);
					//String logo = rjson.getString(User.keyLogo);
					String userid = rjson.getString(User.keyUserId);
					User u = new User(userid, "", nickname, gender, birthday, type, gmai, time,"");
					new Database(LoginActivity.this).setUser(u);
					Intent returnIntent = new Intent();
					returnIntent.putExtra("result", nickname);
					returnIntent.putExtra("userid", userid);	
					
					setResult(RESULT_OK, returnIntent);
					finish();
				}
			} catch (JSONException e) {
				Log.e("error",e.getMessage());
				e.printStackTrace();
			}
			
			//Intent returnIntent = new Intent();
			//returnIntent.putExtra("result", etnickname.getText().toString());
			//setResult(RESULT_OK, returnIntent);
			//finish();
		}
	}
	class AsyntaskLoginWithSocial extends AsyncTask<String, Void, String>
	{
		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progress = ProgressDialog.show(LoginActivity.this, "",
					getResources().getString(R.string.logining), true);
		}
		@Override
		protected String doInBackground(String... params) {
			return new JsonParse().loginAccountWithSocial(params,LoginActivity.this);
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			progress.dismiss();
			try {
				JSONObject json = new JSONObject(result);
				String r = json.getString(Config.result);
				if(r.equalsIgnoreCase(Config.norow)){
					Utility.ShowAlert(LoginActivity.this, getResources().getString(R.string.errortitlelogin), getResources().getString(R.string.errormessagelogin));
				} 
				else{
					JSONObject rjson = json.getJSONArray(Config.result).getJSONObject(0);
					String gmai = rjson.getString(User.keyGmail);
					String nickname = rjson.getString(User.keyNickName);
					//String userName = rjson.getString(User.keyUserName);
					String birthday = rjson.getString(User.keyBirthday);
					String type = rjson.getString(User.keyType);
					String gender = rjson.getString(User.keyGender);
					String time = rjson.getString(User.keyTime);
					String userid = rjson.getString(User.keyUserId);
					//String logo = rjson.getString(User.keyLogo);
					User u = new User(userid, "", nickname, gender, birthday, type, gmai, time,"");
					new Database(LoginActivity.this).setUser(u);
					Intent returnIntent = new Intent(); 
					returnIntent.putExtra("result", nickname);
					returnIntent.putExtra("userid", userid);	
					
					setResult(RESULT_OK, returnIntent);
					finish();
				}
			} catch (JSONException e) {
				Log.e("error",e.getMessage());
				e.printStackTrace();
			}
		}
	}
	public void setEditTextFocus(EditText et, boolean isFocused)
	{
		et.setCursorVisible(isFocused);
		et.setFocusable(isFocused);
		et.setFocusableInTouchMode(isFocused);

	    if (isFocused) 
	    {
	    	et.requestFocus();
	    }
	    ShowKeyboard(et);
	    /*((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(et,0);
	    getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);*/
	}
	//show keyboard
	public void ShowKeyboard(EditText et)
	{
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY); // show
	}
	public void hideKeyboard(EditText et)
	{
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
		getWindow().setSoftInputMode(
			      WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
	}
	
}
